package com.online.college.portal.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.egzosn.pay.ali.api.AliPayConfigStorage;
import com.egzosn.pay.ali.api.AliPayService;
import com.egzosn.pay.common.api.PayService;
import com.online.college.common.pay.AliPayConfig;
import freemarker.log.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.online.college.core.auth.domain.AuthUser;
import com.online.college.core.auth.service.IAuthUserService;
import com.online.college.core.consts.CourseEnum;
import com.online.college.core.consts.domain.ConstsSiteCarousel;
import com.online.college.core.consts.service.IConstsSiteCarouselService;
import com.online.college.core.course.domain.Course;
import com.online.college.core.course.domain.CourseQueryDto;
import com.online.college.core.course.service.ICourseService;
import com.online.college.portal.business.IPortalBusiness;
import com.online.college.portal.vo.ConstsClassifyVO;

import javax.servlet.http.HttpServletRequest;

/**
 * 网站主页
 */
@Controller
@RequestMapping()
public class PortalController {
	static final Logger log = Logger.getLogger("UserController");
	@Autowired
	private IPortalBusiness portalBusiness;
	
	@Autowired
	private IConstsSiteCarouselService siteCarouselService;
	
	@Autowired
	private ICourseService courseService;
	
	@Autowired
	private IAuthUserService authUserService;
	
	
	/**
	 * 首页
	 */
	@RequestMapping("/index")
	public ModelAndView index(){
		ModelAndView mv = new ModelAndView("index");
		
		//加载轮播
		List<ConstsSiteCarousel> carouselList = siteCarouselService.queryCarousels(4);
		mv.addObject("carouselList", carouselList);
		
		//课程分类(一级分类）
		List<ConstsClassifyVO> classifys = portalBusiness.queryAllClassify();
		
		//课程推荐
		portalBusiness.prepareRecomdCourses(classifys);
		mv.addObject("classifys", classifys);
		
		
		//获取5门实战课推荐，根据权重（weight）进行排序
		CourseQueryDto queryEntity = new CourseQueryDto();
		queryEntity.setCount(5);//5门
		queryEntity.setFree(CourseEnum.FREE_NOT.value());//非免费的：实战课
		queryEntity.descSortField("weight");//按照weight降序排列
		List<Course> actionCourseList = this.courseService.queryList(queryEntity);
		mv.addObject("actionCourseList", actionCourseList);
		
		//获取5门免费课推荐，根据权重（weight）进行排序
		queryEntity.setFree(CourseEnum.FREE.value());//非免费的：实战课
		List<Course> freeCourseList = this.courseService.queryList(queryEntity);
		mv.addObject("freeCourseList", freeCourseList);
		
		//获取7门java课程，根据权重（学习数量studyCount）进行排序
		queryEntity.setCount(7);
		queryEntity.setFree(null);//不分实战和免费类别
		queryEntity.setSubClassify("java");//java分类
		queryEntity.descSortField("studyCount");//按照studyCount降序排列
		List<Course> javaCourseList = this.courseService.queryList(queryEntity);
		mv.addObject("javaCourseList", javaCourseList);
		
		//加载讲师
		List<AuthUser> recomdTeacherList = authUserService.queryRecomd();
		mv.addObject("recomdTeacherList", recomdTeacherList);
		
		return mv;
	}
    /**
     * 支付验证
     */
    @RequestMapping("/success")
    public ModelAndView pay(HttpServletRequest request) throws IOException{
        ModelAndView mv = new ModelAndView("success");

		try {
			payBackBefore(request);
		}catch (Exception ee){
			ee.getMessage();
			mv.addObject("curNav","error");
			return mv;
		}
		mv.addObject("curNav","success");
        return mv;
    }
	/**
	 * 支付宝回调接口验证
	 * @param request
	 * @return
	 * @throws IOException
	 */

	public String payBackBefore(HttpServletRequest request) throws IOException {
		log.debug("收到支付回调....");
        System.out.println("收到支付回调....");
		PayService service = null;
		//支付宝支付
		AliPayConfig alipayConfig = new AliPayConfig();

		AliPayConfigStorage aliPayConfigStorage = new AliPayConfigStorage();
		aliPayConfigStorage.setPid(alipayConfig.getPid());
		aliPayConfigStorage.setAppId(alipayConfig.getAppId());
		aliPayConfigStorage.setKeyPublic(alipayConfig.getAlipayPublicKey());
		aliPayConfigStorage.setKeyPrivate(alipayConfig.getPrivateKey());
		aliPayConfigStorage.setNotifyUrl(alipayConfig.getNotifyUrl());
		aliPayConfigStorage.setReturnUrl("http://www.qzdvfx.com/user/mymoney.html");
		aliPayConfigStorage.setSignType(alipayConfig.getSignType());
		//	aliPayConfigStorage.setSeller("");
		aliPayConfigStorage.setInputCharset("utf-8");
		//是否为测试账号，沙箱环境
		aliPayConfigStorage.setTest(alipayConfig.getIsTest());

		service =  new AliPayService(aliPayConfigStorage);
		log.debug("service 初始化完成...");
        System.out.println("service 初始化完成...");
		//获取支付方返回的对应参数
		Map<String, Object> params = service.getParameter2Map(request.getParameterMap(), request.getInputStream());
		log.debug("返回参数："+params);
        log.debug("params.size()======"+params.size());
        System.out.println("返回参数："+params);
		if (null == params) {
            System.out.println("service 初始化完成...");
			return service.getPayOutMessage("fail", "失败").toMessage();
		}

		//校验
		if (service.verify(params)) {
			//这里处理业务逻辑
            System.out.println("效验成功。");
			//......业务逻辑处理块........
			log.debug("效验成功。");
			return service.getPayOutMessage("success", "成功").toMessage();
		}
		log.debug("效验失败。");
        System.out.println("效验失败。...");
		return service.getPayOutMessage("fail", "失败").toMessage();
	}


}

